<template>
  <div class="contract-add">
    <ft-dialog v-if="dialogVisible" :visible.sync="dialogVisible" width="600px" title="合同制作流程发起" height="297px"
               @close="onCancel">
      <el-form ref="dataRef" class="contract-add_form" :model='entityData'
               size='small' inline :rules="rules" v-loading="loading">
        <el-row>
          <el-col>
            <ft-form-item label='项目名称' prop='projectId'>
              <ft-project-info ref="ftProjectInfo" source-bill-type="CONTRACT_MAKE" v-model='entityData.projectId'
                               @change="onChange"></ft-project-info>
            </ft-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ft-form-item label='客户名称:' prop='customerName'>
              <ft-input v-model='entityData.customerName' placeholder="客户名称" :disabled="true"/>
            </ft-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ft-form-item label='证件号码:' prop='identityNo'>
              <ft-input v-model='entityData.identityNo' placeholder="证件号码" :disabled="true"/>
            </ft-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <ft-form-item label='项目金额:' prop='projectAmt'>
              <ft-input v-model='entityData.projectAmt' placeholder="项目金额" :disabled="true"/>
            </ft-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <ft-form-item label='项目余额:' prop='projectBalance'>
              <ft-input v-model='entityData.projectBalance' placeholder="项目余额" :disabled="true"/>
            </ft-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ft-form-item label='租赁类型:' prop='productMinEm'>
              <ft-enum-select
                  :editing='false'
                  v-model="entityData.productMinEm"
                  service-name="ncls-bms"
                  type-name="productMin"
                  :multiple="false"
                  :include="['SaleLeaseback','DirectLease']"
                  clearable
                  size="small">
              </ft-enum-select>
            </ft-form-item>
          </el-col>
        </el-row>
        <el-row v-if="entityData.spvBusinessEm">
          <el-col>
            <ft-form-item label="是否SPV:" prop="spvBusinessEm">
              <ft-enum-select v-model='entityData.spvBusinessEm'
                              service-name='ncls-bms'
                              type-name='yesOrNo'
                              :editing='false'>
              </ft-enum-select>
            </ft-form-item>
          </el-col>
        </el-row>
        <el-row v-if="entityData.spvBusinessEm">
          <el-col>
            <ft-form-item label='组织机构:' prop='organizationId'>
              <ft-org-info ref="ftOrgInfo" v-model='entityData.organizationId' @change="orgOnChange"></ft-org-info>
            </ft-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ft-form-item label='合同金额' prop='contAmt'>
              <ft-number-input-unit v-model='entityData.contAmt'
                                    :percentUtil="true"
                                    :companyUnit="amountUnit"
                                    :precision='[16,2]'>
              </ft-number-input-unit>
            </ft-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ft-form-item label='是否关联' prop='ifChoose'>
              <ft-enum-select v-model='entityData.ifChoose'
                              service-name='ncls-bms'
                              type-name='yesOrNoNum'
                              :editing='true'>
              </ft-enum-select>
            </ft-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isShow">
          <el-col>
            <ft-form-item label='合同号' prop='contNum'>
              <ft-cont-info ref="ftContInfo"  v-model='entityData.contNum' :projectId="this.entityData.projectId" @contNumMethod="contNumMethod"></ft-cont-info>
            </ft-form-item>
          </el-col>
        </el-row>
        <hr>
        <div class="form-floor_buttons">
          <el-button size="small" @click="onCancel" :disabled="loading">取消</el-button>
          <el-button class="save-button" type="primary" size="small" :disabled="loading" @click="onSave">保存
          </el-button>
        </div>
      </el-form>
    </ft-dialog>
  </div>
</template>

<script>
import FtProjectInfo from "./ft/FtProjectInfo"
import FtContInfo from "./ft/FtContInfo"
import FtOrgInfo from "./ft/FtOrgInfo"

export default {
  name: "ContractAdd",
  components: {FtProjectInfo, FtOrgInfo,FtContInfo},
  data() {
    return {
      dialogVisible: false,
      loading: false,
      entityData: {},
      isShow:false,
      amountUnit: '元',
      rules: {
        projectId: [{required: true, message: '项目名称不能为空', trigger: 'blur'}],
        organizationId: [{required: true, message: '组织机构不能为空', trigger: 'blur'}],
        ifChoose: [{required: true, message: '请选择', trigger: 'blur'}],
        contAmt: [{required: true, message: '合同金额不能为空', trigger: 'change'},
          {pattern: /^\d+(\.{0,2}\d+){0,2}$/, message: '请输入正确的合同金额', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value > this.entityData.projectBalance) {
                return callback(new Error('项目余额不足，请检查并重新输入合同金额！'));
              }
              return callback();
            }, trigger: 'blur'
          }
        ]
      }
    }
  },

  watch:{
    "entityData.ifChoose":function(val){
      if(this.entityData.ifChoose == 1 && this.entityData.projectId){
        this.isShow = true
      }else if(this.entityData.ifChoose == 2){
        this.isShow = false
      }
    },
  },

  methods: {
    onShowCancel(){
        this.dialogVisible = true
    },
    contNumMethod(val){
      this.entityData.contNum = val
    },
    // 取消或返回
    onCancel() {
      this.$refs.dataRef.clearValidate()
      this.$refs['ftProjectInfo'].crearData()
      if (this.entityData.spvBusinessEm) {
        this.$refs['ftOrgInfo'].crearData()
      }
      this.dialogVisible = false
      this.entityData = {}
      this.isShow = false
    },
    onChange(val) {
      this.$set(this.entityData, 'projectId', val.projectId)
      this.$set(this.entityData, 'projectName', val.projectName)
      this.$set(this.entityData, 'customerName', val.customerName)
      this.$set(this.entityData, 'identityNo', val.identityNo)
      this.$set(this.entityData, 'productMinEm', val.productName)
      this.$set(this.entityData, 'spvBusinessEm', val.spvBusinessEm)
      this.$set(this.entityData, 'customerId', val.customerId)
      this.$set(this.entityData, 'projectAmt', val.projectAmt)
      this.$set(this.entityData, 'projectBalance', val.projectBalance)
      this.$set(this.entityData, 'recTypeEm',val.recTypeEm)
      this.$set(this.entityData, 'contNum',null)
      this.$set(this.entityData, 'ifChoose','1')
      if(this.$refs.ftContInfo!=undefined){
        this.$refs.ftContInfo.contNum = null
        this.$refs.ftContInfo.str = []
        this.$refs.ftContInfo.request(this.entityData.projectId)
      }
      this.entityData.isShow = true
      this.$set(this.entityData, 'contAmt', val.projectBalance < 0.00 ? 0.00 : val.projectBalance)
      this.$refs.dataRef.clearValidate('projectId')
    },
    orgOnChange(val) {
      this.$set(this.entityData, 'organizationId', val.orgId)
      this.$refs.dataRef.clearValidate('organizationId')
    },
    // 保存
    onSave() {
      // 防止重复操作
      if (this.loading) {
        return
      }
      // if(this.entityData.)
      this.$refs.dataRef.validate(validate => {
        if (validate) {
          this.$http.get('/joys-rest/ncls-cms/cust/invoice/'+this.entityData.customerId).then(resp => {
              if(resp.body === ""||resp.body === null){
                 this.$message.error("未添加开票信息，请维护后发起！")
              }else{
                this.loading = true
                let url = "/joys-rest/ncls-bms/contract/save"
                this.$http.post(url, this.entityData).then(resp => {
                  let contractId = resp.body.contractId
                  if (contractId) {
                    this.onCancel();
                    //刷新新建合同制作的合同余额
                    this.$refs['ftProjectInfo'].request()
                    //this.$emit("onSuccess", contractId)
                    let params = {
                      contractId: contractId,
                      billStatus: resp.body.billStatus
                    }
                    this.$emit('changeToDetails', params)
                  } else {
                    this.$message.error("新增失败！")
                  }
                }, resp => {
                  if (resp.body) {
                    this.$message.error(resp.body.message || "新增失败！")
                  } else {
                    this.$message.error("新增失败！")
                  }
                }).finally(() => {
                  this.loading = false
                })
             }
         });
        }
      })
    },
  }
}
</script>

<style lang="less" scope>

// .el-select-dropdown{
//   width: 336px !important;
// }
.el-select-dropdown__item {
  overflow: visible;
}

.contract-add {
  background-color: #FFFFFF;

  .contract-add_return {
    margin: 12px 24px;
  }

  hr {
    border: none;
    height: 1px;
    margin: 0;
    background-color: rgba(179, 179, 179, 0.20);
  }

  .contract-add_form {
    margin: 20px 24px 0;
    padding-top: 24px;
    padding-right: 24px;
    background-color: #F1F7FD;

    hr {
      border: none;
      height: 1px;
      margin: 24px 0 0;
      background-color: rgba(179, 179, 179, 0.20);
    }

    .form-floor_buttons {
      width: 100%;
      height: 62px;
      display: flex;
      align-items: center;
      justify-content: flex-end;

      .save-button {
        margin-left: 16px;
        margin-right: 30px;
      }

    }
  }
}
</style>
